package wifi_locator_client.just.wzy.wifi_locator_client;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.net.wifi.ScanResult;
import android.os.Handler;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.Socket;
import java.util.List;

/**
 * Created by wzy on 15-4-11.
 * 数据传输管理
 */
public class TransmissionManager {
    private Socket socket;
    private String host;
    private int port;
    private boolean isConnected = false;
    private Context activityContext;
    private BufferedWriter bufferedWriter;
    private BufferedReader bufferedReader;
    private List<ScanResult> scanResults;

    private String location;

    public TransmissionManager(String _host, int _port, Context _context, List<ScanResult> _scanResults) {
        host = _host;
        port = _port;
        activityContext = _context;
        scanResults = _scanResults;
    }

    /**
     * 发送信息
     * @param mode 发送模式
     *             0    同步信息发送
     *             1    定位信息发送
     */
    public void sendMessage(int mode) {
        switch (mode) {
            case 0:
                new Thread() {
                    @Override
                    public void run() {
                        super.run();

                        try {
                            socket = new Socket(host, port);
                            isConnected = true;
                        } catch (Exception e) {

                            isConnected = false;
                        }
                        Message msg = new Message();
                        if (isConnected) {
                            msg.what = 0;
                            handler.sendMessage(msg);
                        } else {
                            msg.what = 1;
                            handler.sendMessage(msg);
                        }

                    }
                }.start();
                break;
            case 1:
                new Thread() {
                    @Override
                    public void run() {
                        super.run();

                        try {
                            socket = new Socket(host, port);
                            isConnected = true;

                            Message msg = new Message();
                            if (isConnected) {
                                bufferedWriter = new BufferedWriter
                                        (new OutputStreamWriter(socket.getOutputStream()));
                                bufferedReader = new BufferedReader(new InputStreamReader(socket.getInputStream()));


                                bufferedWriter.write("/|");
                                if (!scanResults.isEmpty())
                                    for (int i = 0; i < scanResults.size(); i++) {
                                        bufferedWriter.write(scanResults.get(i).level+100
                                                + "|" + scanResults.get(i).BSSID + " ");
                                    }
                                //bufferedWriter.write("\n");
                                bufferedWriter.flush();
                                location = bufferedReader.readLine();
                                bufferedReader.close();

                                bufferedWriter.close();

                                msg.what = 2;
                                handler.sendMessage(msg);


                            } else {
                                msg.what = 3;
                                handler.sendMessage(msg);
                            }
                        } catch (Exception e) {
                            isConnected = false;
                        }
                    }
                }.start();
                break;
        }
    }

    /**
     * 获取地点名词
     * @return  地点名称
     */
    public String getLocation() {
        return location;

    }

    /**
     * 提示输入地点名称对话框
     */
    private void createDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(activityContext);
        LayoutInflater factory = LayoutInflater.from(activityContext);
        final View textEntryView = factory.inflate(R.layout.dialog_layout, null);
        builder.setTitle("输入地点");
        builder.setView(textEntryView);
        builder.setIcon(android.R.drawable.ic_dialog_info);
        builder.setPositiveButton("确认", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                EditText location = (EditText) textEntryView.findViewById(R.id.location);
                String locationName = location.getText().toString();
                try {

                    bufferedWriter = new BufferedWriter
                            (new OutputStreamWriter(socket.getOutputStream()));
                    bufferedWriter.write(locationName + "|");
                    if (!scanResults.isEmpty())
                        for (int i = 0; i < scanResults.size(); i++) {
                            bufferedWriter.write(scanResults.get(i).level + 100
                                    + "|" + scanResults.get(i).BSSID + " ");
                        }
                    //bufferedWriter.write("\n");
                    bufferedWriter.flush();
                    bufferedWriter.close();
                    // handler.sendEmptyMessage(0);
                } catch (Exception e) {
                    //isConnected = false;
                    e.printStackTrace();
                }
            }
        });
        builder.setNegativeButton("取消", null);
        builder.create().show();
    }

    /**
     * handler监听
     */
    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);

            switch (msg.what) {
                case 0:
                    Toast.makeText(activityContext,
                            "连接成功，请输入地点", Toast.LENGTH_SHORT).show();
                    createDialog();
                    break;
                case 1:
                    Toast.makeText(activityContext,
                            "连接失败，请检查网络", Toast.LENGTH_SHORT).show();
                    break;
                case 2:
                    Toast.makeText(activityContext,
                            "连接成功", Toast.LENGTH_SHORT).show();
                    try {
                        LocateActivity.locateHandler.sendEmptyMessage(0);
                    } catch (Exception e) {
                        //isConnected = false;
                        e.printStackTrace();
                    }
                    break;
                case 3:
                    Toast.makeText(activityContext,
                            "连接失败，请检查网络", Toast.LENGTH_SHORT).show();
                    break;

                default:
                    break;

            }
        }
    };


}
